package com.ruoyi.web.controller.initData;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.dao.SysPostDao;
import com.ruoyi.system.domain.dao.SysUserDao;
import com.ruoyi.system.domain.dao.SysUserPostDao;
import com.ruoyi.system.mapper.SysPostDaoMapper;
import com.ruoyi.system.mapper.SysUserDaoMapper;
import com.ruoyi.system.mapper.SysUserPostDaoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserOrderNumInit {

    @Autowired
    private SysUserDaoMapper sysUserDaoMapper;

    @Autowired
    private SysUserPostDaoMapper sysUserPostDaoMapper;
    @Autowired
    private SysPostDaoMapper sysRoleDaoMapper;

    /**
     * 初始化 用户排序
     */
    public void initUserSort() {
        List<SysUserDao> list = sysUserDaoMapper.selectList(new QueryWrapper<>());
        if (list != null && list.size() > 0) {
            list.stream().forEach(item -> {
                // userUuid=b96e1852522a46399b914fcd8e798d2c,empId=15d41a949a5e487ca6e9ff37f2f60f1e
                if (StringUtils.isEmpty(item.getOldData())) {
                    return;
                }
                LambdaQueryWrapper<SysUserPostDao> lqw = new LambdaQueryWrapper<SysUserPostDao>()
                        .likeRight(SysUserPostDao::getUserId, item.getUserId());
                List<SysUserPostDao> userPostList = sysUserPostDaoMapper.selectList(lqw);
                if (userPostList != null && userPostList.size() > 0) {
                    userPostList.stream().forEach(userPost -> {
                        LambdaQueryWrapper<SysPostDao> lqw2 = new LambdaQueryWrapper<SysPostDao>()
                                .likeRight(SysPostDao::getPostId, userPost.getPostId());
                        List<SysPostDao> sysPostList = sysRoleDaoMapper.selectList(lqw2);
                        if (sysPostList != null && sysPostList.size() > 0) {
                            int postSort = sysPostList.stream().mapToInt(sysPost -> sysPost.getPostSort())
                                    .min().getAsInt();
                            item.setOrderNum(Float.parseFloat(String.valueOf(postSort)));
                            sysUserDaoMapper.updateById(item);
                        }
                    });
                }
            });
        }
    }
}
